package com.hezhi.project.weixin.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.hezhi.common.utils.DateUtils2;
import com.hezhi.framework.config.MyConfig;
import com.hezhi.framework.web.controller.BaseController;
import com.hezhi.framework.web.domain.AjaxResult;
import com.hezhi.project.module.abnormal.domain.Abnormal;
import com.hezhi.project.module.abnormal.service.IAbnormalService;
import com.hezhi.project.module.leave.domain.Leave;
import com.hezhi.project.module.leave.service.ILeaveService;
import com.hezhi.project.module.notice.domain.Notice;
import com.hezhi.project.module.notice.service.INoticeService;
import com.hezhi.project.module.parent.domain.Parent;
import com.hezhi.project.module.parent.service.IParentService;
import com.hezhi.project.module.recipient.domain.Recipient;
import com.hezhi.project.module.recipient.service.IRecipientService;
import com.hezhi.project.module.student.domain.Student;
import com.hezhi.project.module.student.service.IStudentService;
import com.hezhi.project.module.teacher.domain.Teacher;
import com.hezhi.project.module.teacher.service.ITeacherService;
import com.hezhi.project.weixin.utils.SmsUtils;
import com.hezhi.project.weixin.utils.WeChatUtils;

/**
 * 微信接口类
 * 
 * @author 徐伦
 *
 */
@Controller
@RequestMapping("/weixin")
public class WeiXinController extends BaseController {

	@Autowired
	private IParentService parentService;
	@Autowired
	private IStudentService studentService;
	@Autowired
	private IAbnormalService abnormalService;
	@Autowired
	private INoticeService noticeService;
	@Autowired
	private IRecipientService recipientService;
	@Autowired
	private ILeaveService leaveService;
	@Autowired
	private ITeacherService teacherService;

	private String prefix = "weixin";

	@Autowired
	private MyConfig myConfig;

	/**
	 * 入口
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@GetMapping("/entrance")
	public String entrance(HttpServletRequest request, HttpServletResponse response, Model model) {
		String url = request.getScheme() + "://" + request.getServerName() + request.getContextPath() + "/weixin/code";
		String content = WeChatUtils.URL_AUTHORIZE.replace("APPID", myConfig.getWeixin().get("appid"))
				.replace("REDIRECT_URI", url).replace("SCOPE", "snsapi_base");
		model.addAttribute("url", content);
		return prefix + "/entrance";
	}

	/**
	 * 微信返回code
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/code")
	public String getCode(String code, String state, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		if (code == null || "".equals(code)) {
			return "拉取个人信息失败";
		}
		JSONObject jsonObject = WeChatUtils.connect_getOpenid(code);
		HttpSession session = request.getSession(true);
		session.setAttribute("OPENID", jsonObject.getString("openid"));
		return "redirect:index";
	}

	/**
	 * 登录页面
	 * 
	 * @return
	 */
	@GetMapping("/login")
	public String login() {
		return prefix + "/login";
	}

	/**
	 * 家长首页
	 * 
	 * @return
	 */
	@GetMapping("/index")
	public String index(HttpServletRequest request, Model model) {
		HttpSession session = request.getSession(true);
//		Object openId = session.getAttribute("OPENID");
		Object openId = "owbYs1DXDXVgPfcKmyRtuPlOhwsA";
//		Object openId = "13928841271";
		if (openId != null) {
			Parent parent = new Parent();
			parent.setOpenId(openId.toString());
			List<Parent> listParent = parentService.selectParentList(parent);
			if (listParent.size() > 0) {
				model.addAttribute("parent", listParent.get(0));
				List<String> students = new ArrayList<String>();
				for (Parent p : listParent) {
					students.add(p.getStudentNumber());
				}
				session.setAttribute("students", students);
				session.setAttribute("parent", listParent.get(0));
				return prefix + "/index";
			} else {
				Teacher teacher = new Teacher();
				teacher.setOpenId(openId.toString());
				teacher = teacherService.selectTeacherByOpenId(teacher);
				if (teacher != null) {
					session.setAttribute("teacher", teacher);
					model.addAttribute("teacher", teacher);
					return prefix + "/teacherIndex";
				} else {
					return "redirect:login";
				}
			}
		}
		return "redirect:login";
	}

	/**
	 * 获取短信验证码
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getMessageCode")
	public AjaxResult getMessageCode(HttpServletRequest request, HttpServletResponse response, String phone) {
		HttpSession session = request.getSession(true);
		boolean b = false;
		// 验证家长手机号码是否存在并且为绑定微信
		Parent parent = new Parent();
		parent.setTelephone(phone);
		parent.setRemark("openid");
		List<Parent> listParent = parentService.selectParentList(parent);
		if (listParent.size() == 0) {
			Teacher teacher = new Teacher();
			teacher.setTelphone(phone);
			teacher.setRemark("openid");
			List<Teacher> listTeacher = teacherService.selectTeacherList(teacher);
			if (listTeacher.size() == 0) {
				return error(1, "手机号不存在或已被绑定");
			} else {
				b = true;
			}
		} else {
			b = true;
		}
		if (b) {
			// 生成六位随机数
			Random random = new Random();
			String result = "";
			for (int i = 0; i < 6; i++) {
				result += random.nextInt(10);
			}
			if (SmsUtils.sendSms(phone, result)) {
//			if(sendsms.send(phone, result)){
				session.setAttribute(phone, result);
				return success(result);
			} else {
				return error(1, "系统错误");
			}
		} else {
			return error(1, "手机号不存在或已被绑定");
		}
	}

	/**
	 * 验证短信验证码是否正确
	 * 
	 * @param request
	 * @param response
	 * @param phone
	 * @param code
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/checkMessageCode")
	public boolean checkMessageCode(HttpServletRequest request, HttpServletResponse response, String phone,
			String code) {
		HttpSession session = request.getSession(true);
		Object result = session.getAttribute(phone);
//		if (code.equals(result)) {
//			session.removeAttribute(phone);
//			return true;
//		} else {
//			return false;
//		}
		return true;
	}

	/**
	 * 注册
	 * 
	 * @param phone
	 * @return
	 */
	@RequestMapping("/register")
	public String register(HttpServletRequest request, String phone, String role) {
		HttpSession session = request.getSession(true);
		Object openId = session.getAttribute("OPENID");
		if (openId != null) {
			if ("1".equals(role)) {
				Parent parent = new Parent();
				parent.setTelephone(phone);
				parent.setOpenId(openId.toString());
				parentService.updateParentByTelephone(parent);
			} else {
				Teacher teacher = new Teacher();
				teacher.setTelphone(phone);
				teacher.setOpenId(openId.toString());
				teacherService.updateTeacherByTelphone(teacher);
			}
			return "redirect:index";
		} else {
			return "redirect:entrance";
		}
	}

	/**
	 * 显示学生信息
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/studentInfo")
	public String studentInfo(HttpServletRequest request, Model model) {
		HttpSession session = request.getSession(true);
		List<String> students = (List<String>) session.getAttribute("students");
		Student student = new Student();
		student.setListString(students);
		List<Student> listStudent = studentService.selectStudentList(student);
		model.addAttribute("parent", session.getAttribute("parent"));
		model.addAttribute("listStudent", listStudent);
		return prefix + "/studentInfo";
	}

	/**
	 * 查询进出记录
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/inout")
	public String inout(HttpServletRequest request, Model model) {
		HttpSession session = request.getSession(true);
		List<String> students = (List<String>) session.getAttribute("students");
		Abnormal abnormal = new Abnormal();
		abnormal.setListString(students);
		List<Abnormal> listAbnormal = abnormalService.selectAbnormalList(abnormal);
		model.addAttribute("listAbnormal", listAbnormal);
		return prefix + "/inout";
	}

	/**
	 * 查询进出记录详情
	 * 
	 * @param abnormalId
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/inoutInfo")
	public String inoutInfo(int abnormalId, HttpServletRequest request, Model model) {
		Abnormal abnormal = new Abnormal();
		abnormal.setAbnormalId(abnormalId);
		List<Abnormal> listAbnormal = abnormalService.selectAbnormalList(abnormal);
		model.addAttribute("listAbnormal", listAbnormal);
		return prefix + "/inoutInfo";
	}

	/**
	 * 查询通知数据
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/notice")
	public String notice(HttpServletRequest request, Model model) {
		HttpSession session = request.getSession(true);
		Parent parent = (Parent) session.getAttribute("parent");
		Recipient recipient = new Recipient();
		recipient.setRecipient(parent.getParentId() + "");
		recipient.setRole("1");
		List<Notice> list = noticeService.selectNoticeListByRecipient(recipient);
		model.addAttribute("listNotice", list);
		return prefix + "/notice";
	}

	/**
	 * 通知详情
	 * 
	 * @param request
	 * @param noticeId
	 * @param model
	 * @return
	 */
	@RequestMapping("/noticeInfo")
	public String noticeInfo(HttpServletRequest request, int noticeId, Model model) {
		HttpSession session = request.getSession(true);
		Parent parent = (Parent) session.getAttribute("parent");
		// 查询消息详细
		Notice notice = noticeService.selectNoticeById(noticeId);
		model.addAttribute("notice", notice);
		// 设置消息已读
		Recipient recipient = new Recipient();
		recipient.setNoticeId(noticeId);
		recipient.setRecipient(parent.getParentId() + "");
		recipient.setIfRead("1");
		recipientService.updateRecipient(recipient);
		return prefix + "/noticeInfo";
	}

	/**
	 * 请假申请列表
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/leaveList")
	public String leaveList(HttpServletRequest request, Model model) {
		HttpSession session = request.getSession(true);
		Parent parent = (Parent) session.getAttribute("parent");
		Leave leave = new Leave();
		leave.setParentNumber(parent.getParentId() + "");
		List<Leave> list = leaveService.selectLeaveList(leave);
		model.addAttribute("list", list);
		return prefix + "/leaveList";
	}

	/**
	 * 新增请假
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/addLeave")
	public String addLeave(HttpServletRequest request, Model model) {
		HttpSession session = request.getSession(true);
		List<String> students = (List<String>) session.getAttribute("students");
		Student student = new Student();
		student.setListString(students);
		List<Student> listStudent = studentService.selectStudentList(student);
		model.addAttribute("teacherNumber", listStudent.get(0).getClasses().getHeadmasterId());
		model.addAttribute("teacherNumberName", listStudent.get(0).getClasses().getTeacher().getName());
		model.addAttribute("studentNumber", listStudent.get(0).getStudentNumber());
		model.addAttribute("title", "请假_" + listStudent.get(0).getName() + "_" + DateUtils2.getDate("yyyyMMdd"));
		return prefix + "/addLeave";
	}

	/**
	 * 查看请假详情
	 * 
	 * @param leaveId
	 * @param model
	 * @return
	 */
	@RequestMapping("/leaveInfo")
	public String leaveInfo(int leaveId, Model model) {
		Leave leave = leaveService.selectLeaveById(leaveId);
		model.addAttribute("leave", leave);
		return prefix + "/leaveInfo";
	}

	/**
	 * 保存请假信息
	 * 
	 * @param leave
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("saveLeave")
	public AjaxResult saveLeave(Leave leave, HttpServletRequest request) {
		HttpSession session = request.getSession(true);
		Parent parent = (Parent) session.getAttribute("parent");
		leave.setParentNumber(parent.getParentId() + "");
		leaveService.insertLeave(leave);
		return success();
	}

	/**
	 * 教师查看请假申请
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/leaveListByTeacher")
	public String leaveListByTeacher(HttpServletRequest request, Model model) {
		HttpSession session = request.getSession(true);
		Teacher teacher = (Teacher) session.getAttribute("teacher");
		Leave leave = new Leave();
		leave.setTeacherNumber(teacher.getTeacherNumber());
		List<Leave> list = leaveService.selectLeaveList(leave);
		model.addAttribute("list", list);
		return prefix + "/leaveListByTeacher";
	}

	/**
	 * 查看请假详情
	 * 
	 * @param leaveId
	 * @param model
	 * @return
	 */
	@RequestMapping("/leaveInfo2")
	public String leaveInfo2(int leaveId, Model model) {
		Leave leave = leaveService.selectLeaveById(leaveId);
		model.addAttribute("leave", leave);
		return prefix + "/leaveInfo2";
	}

	/**
	 * 修改请假状态
	 * 
	 * @param leave
	 * @return
	 */
	@PostMapping("/updateStatus")
	@ResponseBody
	public AjaxResult updateStatus(Leave leave) {
		int rows = leaveService.updateLeave(leave);
		if (rows > 0) {
			return success();
		}
		return error();
	}
}
